<template>
  <div class="app-container">
    <el-row :gutter="20">
      <!--用户数据-->
      <el-col :span="24" :xs="24">
        <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">

          <el-form-item label="ID" prop="id">
            <el-input v-model="queryParams.id" placeholder="请输入id" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item label="用户名" prop="real_name">
            <el-input v-model="queryParams.username" placeholder="请输入用户名" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item label="手机号码" prop="mobile">
            <el-input v-model="queryParams.mobile" placeholder="请输入手机号码" clearable size="small" style="width: 240px" @keyup.enter.native="handleQuery" />
          </el-form-item>

          <el-form-item label="小区" prop="community_id">
            <el-select v-model="queryParams.community_id" placeholder="请选择小区" >
              <el-option v-for="item in CommunityList" :key="item.id" :label="item.name" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="筹备组" prop="vote_class_id">
            <el-select v-model="queryParams.preparatory_id" placeholder="请选择">
              <el-option v-for="item in PreparatoryDataList" :key="item.id" :label="item.username" :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>

          <el-form-item label="状态" prop="state">
            <el-select v-model="queryParams.state" placeholder="用户状态" clearable size="small" style="width: 240px">
              <el-option v-for="dict in dict.type.sys_normal_disable" :key="dict.value" :label="dict.label" :value="dict.value" />
            </el-select>
          </el-form-item>

          <el-form-item>
            <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
            <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>

        <!-- <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="handleAdd"
              v-hasPermi="['UserController@store']">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="success" plain icon="el-icon-edit" size="mini" :disabled="single" @click="handlePass"
              v-hasPermi="['UserController@update']">修改</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" plain icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleTurn"
              v-hasPermi="['UserController@destroy']">删除</el-button>
          </el-col>
        </el-row> -->

        <el-table v-loading="loading" :data="DataList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="50" align="center" />
          <el-table-column label="ID" align="center" key="id" prop="id" width="100" />
          <el-table-column label="用户名" align="center" key="username" prop="username" width="200" />

          <el-table-column label="手机号码" align="center" key="mobile" prop="mobile" width="120" />


          <el-table-column label="小区" align="center" prop="community" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.community.name }}</span>
            </template>
          </el-table-column>


          <el-table-column label="筹备组" align="center" prop="community" width="180">
            <template slot-scope="scope">
              <span>{{ scope.row.preparatory.username }}</span>
            </template>
          </el-table-column>





          <el-table-column label="状态" align="center" key="state">
            <template slot-scope="scope">
              <el-switch v-model="scope.row.state" active-value="1" inactive-value="0" @change="handleStatusChange(scope.row)"></el-switch>
            </template>
          </el-table-column>


          <el-table-column label="创建时间" align="center" prop="created_at" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.created_at) }}</span>
            </template>
          </el-table-column>
          <el-table-column label="更新时间" align="center" prop="updated_at" width="180">
            <template slot-scope="scope">
              <span>{{ parseTime(scope.row.updated_at) }}</span>
            </template>
          </el-table-column>
          <!-- audit_status 审核状态，1：未提交，2：已提交 3：审核通过 4：审核失败 -->
          <el-table-column label="操作" align="center" width="160" class-name="small-padding fixed-width">
            <template slot-scope="scope">

              <el-button v-if="scope.row.audit_status" size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)" v-hasPermi="['system:post:edit']">修改</el-button>

              <el-button v-if="scope.row.audit_status == 3" size="mini" type="text" @click="handleAudit(scope.row,1)" v-hasPermi="['UserController@update']" :disabled="(scope.row.audit_status == 3)">已通过</el-button>
              <el-button v-else-if="scope.row.audit_status == 4 " size="mini" type="text" @click="handleAudit(scope.row,0)" v-hasPermi="['UserController@destroy']" :disabled="(scope.row.audit_status == 4)">已驳回</el-button>

              <div v-else>
                <el-button v-if="scope.row.audit_status==2" size="mini" type="text" @click="handleAudit(scope.row,1)" v-hasPermi="['UserController@update']">通过</el-button>
                <el-button v-if="scope.row.audit_status==2" size="mini" type="text" @click="handleAudit(scope.row,0)" v-hasPermi="['UserController@update']">驳回</el-button>
              </div>

            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total>0" :total="total" :page.sync="queryParams.page" :limit.sync="queryParams.pageSize" @pagination="getAuditList" />
      </el-col>
    </el-row>






    <!-- 添加开始 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" append-to-body width="32%">

      <el-form ref="form" :rules="rules" :model="form" label-width="90px" style="height: 800px;">

        <el-form-item label="用户名" prop="username">
          <el-input v-model="form.username" placeholder="请输入用户名" clearable size="small" />
        </el-form-item>

        <el-form-item label="真实姓名" prop="real_name">
          <el-input v-model="form.real_name" placeholder="请输入真实姓名" clearable size="small" />
        </el-form-item>

        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="form.mobile" placeholder="请输入手机号码" clearable size="small" />
        </el-form-item>

        <el-form-item label="开户行" prop="open_bank">
          <el-input v-model="form.open_bank" placeholder="请输入开户行" clearable size="small" />
        </el-form-item>

        <el-form-item label="银行卡号" prop="card_number">
          <el-input v-model="form.card_number" placeholder="请输入银行卡号" clearable size="small" />
        </el-form-item>

        <el-form-item label="结算比例" prop="settlement_ratio">
          <el-input v-model="form.settlement_ratio" placeholder="请输入结算比例" clearable size="small" />
        </el-form-item>



        <el-form-item label="qq" prop="qq">
          <el-input v-model="form.qq" placeholder="请输入qq号" clearable size="small" />
        </el-form-item>

        <el-form-item label="微信" prop="weixin">
          <el-input v-model="form.weixin" placeholder="请输入微信号" clearable size="small" />
        </el-form-item>

        <el-form-item label="身份证正面" prop="identity_front">
          <el-upload :action="upload_url" :on-success="handleFileSuccess" :show-file-list="false" class="avatar-uploader">
            <img style="width: 100px;height: 100px;" v-if="form.identity_front" :src="form.identity_front" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="身份证背面" prop="identity_back">
          <el-upload :action="upload_url" :on-success="handleFileSuccessBack" :show-file-list="false" class="avatar-uploader">
            <img style="width: 100px;height: 100px;" v-if="form.identity_back" :src="form.identity_back" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>

        <el-form-item label="认证视频">
          <el-upload :action="upload_url" :on-success="handleLogSuccessZsf" :show-file-list="false" accept=".mp4" class="avatar-uploader">

            <video v-if="form.auth_video" controls style="width: 300px;height: 160px;">
              <source :src="form.auth_video" type="video/mp4">
            </video>

            <i v-else class="el-icon-plus avatar-uploader-icon"> </i>

          </el-upload>
        </el-form-item>

      </el-form>

      <div slot="footer" class="dialog-footer" style="margin-top: 50px;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 添加结束 -->


  </div>
</template>

<script>
  import * as User from "@/api/system/user";
  import * as Audit from "@/api/system/audit";

  import {
    getToken
  } from "@/utils/auth";
  import {
    treeselect
  } from "@/api/system/role";
  import Treeselect from "@riophae/vue-treeselect";
  import {
    treeselect as menuTreeselect,
    rolePermission
  } from "@/api/system/menu";
  import "@riophae/vue-treeselect/dist/vue-treeselect.css";
  import {
    changeUserBankStatus
  } from "@/api/system/audit";
 import * as Community from "@/api/operation/community";
   import * as Preparatory from "@/api/operation/preparatory";

  export default {
    name: "User",
    dicts: ['sys_normal_disable', 'sys_user_sex'],
    components: {
      Treeselect
    },
    data() {
      return {
          CommunityList: [], //小区列表
              PreparatoryDataList: [],
        upload_url: process.env.VUE_APP_BASE_URL + '/file/upload',
        // 遮罩层
        loading: true,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 用户表格数据
        DataList: null,
        // 弹出层标题
        title: "",
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 部门树选项
        deptOptions: undefined,
        // 是否显示弹出层
        open: false,
        dialog_permission: false,
        form_permission: {
          menuCheckStrictly: false,
          checkList: []
        },
        // 默认密码
        initPassword: undefined,
        // 日期范围
        dateRange: [],
        // 角色选项
        roleOptions: [],
        menuOptions: [],
        // 表单参数
        form: {
          qq: '',
          weixin: '',
        },
        defaultProps: {
          children: "children",
          label: "label"
        },
        // 用户导入参数
        upload: {
          // 是否显示弹出层（用户导入）
          open: false,
          // 弹出层标题（用户导入）
          title: "",
          // 是否禁用上传
          isUploading: false,
          // 是否更新已经存在的用户数据
          updateSupport: 0
        },
        // 查询参数
        queryParams: {
          page: 1,
          pageSize: 10,
          id: null,
          real_name: undefined,
          mobile: undefined,
          state: undefined,
          role_id: undefined
        },
        preparatoryParams: {
          page: 1,
          pageSize: 100
        },
        // 表单校验
        rules: {
          real_name: [{
              required: true,
              message: "用户名称不能为空",
              trigger: "blur"
            },
            {
              min: 2,
              max: 20,
              message: '用户名称长度必须介于 2 和 20 之间',
              trigger: 'blur'
            }
          ],
          username: [{
            required: true,
            message: "用户昵称不能为空",
            trigger: "blur"
          }, ],
          open_bank: [{
              required: true,
              message: "开户行不能为空",
              trigger: "blur"
            },

          ],
          card_number: [{
            required: true,
            message: "银行卡号不能为空",
            trigger: "blur"
          }, ],
          settlement_ratio: [{
            required: true,
            message: "请输入结算比例",
            trigger: "blur"
          }, ],
          // auth_video: [{
          //   required: true,
          //   message: "实名认证视频不能为空",
          //   trigger: "blur"
          // }, ],

          mobile: [{
              required: true,
              message: "手机号不能为空",
              trigger: "blur"
            },
            {
              pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
              message: "请输入正确的手机号码",
              trigger: "blur"
            },
          ]
        },

      };
    },

    created() {

      this.getAuditList();
      this.getCommunityList();
      this.getPreparatoryList();


    },
    methods: {
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.reset();
        const userId = row.id || this.ids;
        Audit.getUserInfo(userId).then(response => {
          this.form = response.data;
          // this.$set(this.form, 'username', response.data.info[0].username)
          // this.$set(this.form, 'qq', response.data.info[0].qq)
          // this.$set(this.form, 'weixin', response.data.info[0].weixin)
          this.open = true;
          this.title = "修改用户";
          this.form.password = "";
        });
      },

      /** 查询筹备组列表 */
      getPreparatoryList() {
        this.loading = true;
        Preparatory.List(this.queryPreparatoryParams).then(response => {
          this.PreparatoryDataList = response.data.rows;
          this.loading = false;
        });
      },


      /** 查询小区列表 */
      getCommunityList() {
        this.loading = true;
        Community.List(this.preparatoryParams).then(response => {
          this.CommunityList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
        });
      },

      //身份证正面
      handleFileSuccess(res) {
        this.form.identity_front = res.data;
      },

      //身份证背面
      handleFileSuccessBack(res) {
        this.form.identity_back = res.data;
      },

      /****上传视频*****/
      handleLogSuccessZsf(res) {
        this.$set(this.form, 'auth_video', res.data);
      },

      /** 提交按钮 */
      submitForm: function() {

        this.$refs["form"].validate(valid => {
          if (valid) {
            if (this.form.id != undefined) {

              Audit.updateUser(this.form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getAuditList();
              });
            } else {
              // User.addUser(this.form).then(response => {
              //   this.$modal.msgSuccess("新增成功");
              //   this.open = false;
              //   this.getList();
              // });
            }
          }
        });
      },






      /** 查询个人认证列表 */
      getAuditList() {
        this.loading = true;
        Audit.getAuditList(this.queryParams).then(response => {
          console.log('人个认证列表', response.data.rows)
          this.DataList = response.data.rows;
          this.total = response.data.total;
          this.loading = false;
        });
      },



      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          real_name: undefined,
          nickname: undefined,
          password: undefined,
          mobile: undefined,
          qq: undefined,
          weixin: undefined,
          state: "0",
          remark: undefined,
          role_ids: []
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.page = 1;
        this.getAuditList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.dateRange = [];
       this.queryParams = {
         page: 1,
         pageSize: 10
       };
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length != 1;
        this.multiple = !selection.length;
      },


      // 用户状态修改
      handleStatusChange(row) {
        console.log(row)
        let text = row.state === "1" ? "启用" : "停用";
        this.$modal.confirm('确认要"' + text + '""' + row.username + '"用户吗？').then(function() {
          return changeUserBankStatus(row.id, row.state);
        }).then(() => {
          this.$modal.msgSuccess(text + "成功");
        }).catch(function() {
          row.state = row.state === "1" ? "1" : "0";
        });
      },



      /** 驳回按钮操作 */
      handleAudit(row, type) {
        //type 0驳回 1通过
        const bank_id = row.id;
        const users_id = row.users_id;
        if (type == 1) {
          var htm = '通过'
        } else {
          var htm = '驳回'
        }

        this.$modal.confirm('是否确认"' + htm + '""' + row.real_name + '"的个人认证？').then(function() {
          return Audit.submitAudit(bank_id, users_id, type);
        }).then(() => {
          this.getAuditList();
          this.$modal.msgSuccess("审核成功");
        }).catch(() => {});
      },







    }
  };
</script>
<style rel="stylesheet/scss" lang="scss">
  .tree-border {
    height: 300px;
    overflow-y: scroll;
  }
</style>


<style lang="scss" scoped>
  ::v-deep .el-dialog__footer {
    padding-top: 40px;
  }
</style>
